package rjeutsky.servlets;

import java.io.IOException;
import java.net.URLEncoder;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import rjeutsky.ControllerWrapper;
import rjeutsky.models.Publication;
import rjeutsky.models.User;
import rjeutsky.validators.interfaces.Validator;

/**
 * Servlet implementation class EditPublicationServlet
 */
@WebServlet("/EditPublication")
public class EditPublicationServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public EditPublicationServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		User currentUser = (User) request.getSession().getAttribute("currentUser");
		if (currentUser != null && ControllerWrapper.getApplicationController().checkIsAdmin(currentUser)) {
			Publication publication;
			try {
				Long id = Long.parseLong(request.getParameter("id"));
				publication = ControllerWrapper.getApplicationController().getPublication(id);
				if (publication == null) {
					response.sendError(404);
					return;
				}
			} catch (NumberFormatException ex) {
				response.sendError(404);
				return;
			}
			
			publication.setName(request.getParameter("name"));
			try {
				long price = Long.parseLong(request.getParameter("price"));
				publication.setPrice(price);
			} catch (NumberFormatException ex) {
				response.sendRedirect("Publications.jsp?validationError=Price+should+be+a+number");
			}
			
			Validator<Publication> v = ControllerWrapper.getApplicationController().getPublicationValidator();
			if (!v.validate(publication)) {
				String message = URLEncoder.encode(v.getValidationErrorMessage().toString(), "UTF-8");
				response.sendRedirect("Publications.jsp?validationError=" + message);
			} 
			else {
				try {
					ControllerWrapper.getApplicationController().updatePublication(publication);
				} catch (SQLException e) {
					response.sendError(500);
					return;
				}
				
				response.sendRedirect("Publications.jsp?infoText=Publication+has+been+created+successfully");
			}
		}
		else {
			response.sendRedirect("Login.jsp");
		}
	}

}
